//
//  YXTimer.m
//  TASWork
//
//  Created by YUSIR on 2018/1/9.
//  Copyright © 2018年 YUSIR All rights reserved.
//

#import "YXTimer.h"
#define AKCTimer_DEFDELAY 5
#define AKCTimer_INTERVAL 5
@interface YXTimer(){
    dispatch_source_t timer;
    AKCTimerTask timerBlock;
}
@end

@implementation YXTimer
@synthesize repeat;
@synthesize delay;
@synthesize interval;
@synthesize loopsNum;
- (void)dealloc
{
    YXLog(@"AKCTimer dealloc");
}

- (instancetype)init:(AKCTimerTask)taskBlock
{
    YXLog(@"AKCTimer init");
    if(!(self = [super init]))return nil;
    self.repeat = NO;
    self.delay = AKCTimer_DEFDELAY;
    self.interval = AKCTimer_INTERVAL;
    self.loopsNum = -1;
    timerBlock = taskBlock;
    return self;
}

- (instancetype)init:(AKCTimerTask)taskBlock repeat:(BOOL)isrepeat delay:(NSTimeInterval)timedelay interval:(NSTimeInterval)timeinterval
{
    YXLog(@"AKCTimer init");
    if(!(self = [super init]))return nil;
    self.repeat = isrepeat;
    self.delay = timedelay > 0 ? timedelay : AKCTimer_DEFDELAY;
    self.interval = timeinterval > 0 ? timeinterval : AKCTimer_INTERVAL;
    self.loopsNum = -1;
    timerBlock = taskBlock;
    return self;
}
- (instancetype)init:(AKCTimerTask)taskBlock repeat:(BOOL)isrepeat repeatLoops:(int)loops delay:(NSTimeInterval)timedelay interval:(NSTimeInterval)timeinterval
{
    YXLog(@"AKCTimer init");
    if(!(self = [super init]))return nil;
    self.repeat = isrepeat;
    self.delay = timedelay > 0 ? timedelay : AKCTimer_DEFDELAY;
    self.interval = timeinterval > 0 ? timeinterval : AKCTimer_INTERVAL;
    self.loopsNum = loops;
    timerBlock = taskBlock;
    return self;
}

- (void)start
{
    
    if (!timer) {
        YXLog(@"AKCTimer start");
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_event_handler(timer, ^{ @autoreleasepool {
            YXLog(@"AKCTimer run");
            if (!self.repeat) {
                [self stop];
            }else{
                if (self.loopsNum==0) {
                    [self stop];
                }else{
                    self.loopsNum--;
                }
            }
            if(timerBlock()){
                [self stop];
            }
        }});
        dispatch_time_t startTime;
        startTime = dispatch_time(DISPATCH_TIME_NOW, (self.delay * NSEC_PER_SEC));
        dispatch_source_set_timer(timer, startTime, self.repeat ? self.interval * NSEC_PER_SEC : DISPATCH_TIME_FOREVER, 0.25);
        dispatch_resume(timer);
    }
}

- (void)stop
{
    @synchronized (timer) {
        if (timer) {
            YXLog(@"AKCTimer stop");
            dispatch_source_cancel(timer);
            timer = NULL;
        }
    }
}

@end
